iT邦幫忙

2024 iThome 鐵人賽

DAY 5
0
自我挑戰組

利用 node.js/express 架設網站系列 第 5

Day-05 express練習(下)

  • 分享至 

  • xImage
  •  

今天會來了解什麼是中介軟體(middleware),以及如何處理錯誤和使用模板引擎來動態生成 HTML

深入了解中介軟體(Middleware):

中介軟體在 Express 應用中扮演著重要角色,它們位於請求和回應之間,允許你對請求和回應進行處理、修改,或者終止請求-回應循環。

  • 基本中介軟體使用:
    在 Express 中使用中介軟體非常簡單,只需使用 app.use() 來設置它們。
    範例:
const express = require('express');
const app = express();

// 全局中介軟體
app.use((req, res, next) => {
    console.log(`Request Method: ${req.method}, URL: ${req.url}`);
    next(); // 繼續到下一個中介軟體或路由
});

app.get('/', (req, res) => {
    res.send('Hello, Express!');
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

在這個範例中,中介軟體會記錄每個請求的 HTTP 方法和 URL。
https://ithelp.ithome.com.tw/upload/images/20240919/20169465hzd1yBp32D.png

  • 創建自定義中介軟體:
    你可以創建自己的中介軟體來執行特定的任務,例如驗證、解析請求數據、日誌記錄等。
const checkAuth = (req, res, next) => {
    if (req.query.auth === 'true') {
        next(); // 驗證通過,繼續處理請求
    } else {
        res.status(403).send('Unauthorized');
    }
};

app.get('/secure', checkAuth, (req, res) => {
    res.send('Welcome to the secure section.');
});

當訪問/secure 路由時,請求中必須包含查詢參數 auth=true,否則返回 403 錯誤。

處理錯誤

在 Express 中,錯誤處理是一個重要的部分。你可以使用錯誤處理中介軟體來捕獲和處理應用中的錯誤。

  • 基礎錯誤處理:
    使用 next() 方法來將錯誤傳遞給 Express 錯誤處理中介軟體。
app.get('/error', (req, res, next) => {
    const error = new Error('Something went wrong!');
    next(error); // 傳遞錯誤
});

// 錯誤處理中介軟體
app.use((err, req, res, next) => {
    console.error(err.stack); // 輸出錯誤堆棧信息
    res.status(500).send('Internal Server Error');
});

使用 EJS 模板引擎:

1.安裝EJS:

npm install ejs 

2.設定EJS作為模板引擎:

app.set('view engine', 'ejs');
app.set('views', './views'); // 設定模板檔案的路徑

3.接著在views的目錄中新增一個indexs.ejs

<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
</head>
<body>
    <h1>Hello, <%= name %>!</h1>
</body>
</html>

4.渲染模板

app.get('/template', (req, res) => {
    res.render('index', { title: 'My Page', name: 'Express' });
});

訪問 /template 時,伺服器會渲染 index.ejs 模板並輸出。


上一篇
Day-04 express練習(上)
下一篇
Day-06 處理靜態文件和連接資料庫
系列文
利用 node.js/express 架設網站26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言